<template>
  <div>
    <common-head :title="title" />
    <div class="wrap2">
      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="img in pics" :key="img.id">
          <img :src="img.pic" alt="" />
        </van-swipe-item>
      </van-swipe>
      <h3>{{ basicInfo.name }}</h3>
      <div class="content" v-html="content"></div>
    </div>
    <!-- 购物车弹出框 -->
    <van-popup  v-model="show" position="bottom" round closeable :style="{ height: '30%' }">
      <div>
        <van-card
          :num="sku.num"
          :price="sku.minPrice"
          :title="sku.name"
          :thumb="sku.pic">
          <template #footer>
            <van-stepper v-model="sku.num" />
            <van-button
             @click="commitItem" type="danger" size="large">确定</van-button>
          </template>
        </van-card>
      </div>
    </van-popup>
    <!-- /购物车弹出框 -->
    <!-- 详情页购物车  -->
    <van-goods-action class="box">
      <van-goods-action-icon
        icon="home-o"
        text="首页"
        @click="$router.push('/home')"
      />
      <van-goods-action-icon
        icon="cart-o"
        :badge="$store.state.cart.items.length || ''"
        text="购物车"
        @click="$router.push('/cart')"
      />
      <van-goods-action-button
        type="danger"
        text="加入购物车"
        @click="showSku"
      />
    </van-goods-action>
    <!-- /详情页购物车 -->

  </div>
</template>

<script>
import CommonHead from 'components/CommonHead'
import { fetchItemDetail, addCart } from 'api'
import { Toast } from 'vant'
export default {
  name: 'detail',
  data () {
    return {
      title: '商品详情',
      basicInfo: {},
      pics: [],
      content: '',
      show: false,
      sku: {
        number: 1
      }
    }
  },
  created () {
    this.fetchDetail()
  },
  methods: {
    commitItem () {
      addCart({
        goodsId: this.sku.id,
        number: this.sku.number,
        token: localStorage.getItem('token')
      }).then(res => {
        if (res.data.code === 0) {
          Toast({
            type: 'success',
            message: '加入成功'
          })
          this.show = false
          this.$store.commit('cart/set_items',
            res.data.data.items
          )
        }
      })
    },
    showSku () {
      this.show = true
    },
    fetchDetail () {
      // 获取商品详情
      fetchItemDetail(this.$route.query.id).then((res) => {
        if (res.data.code === 0) {
          this.basicInfo = res.data.data.basicInfo
          this.pics = res.data.data.pics
          this.title = this.basicInfo.name
          this.sku = {
            ...this.sku,
            ...res.data.data.basicInfo
          }
        }
      })
    }
  },
  components: {
    CommonHead
  }
}
</script>

<style lang="scss" scoped>
.wrap2 {
  padding-top: 46px;
  padding-bottom: 50px;
  .my-swipe {
    img {
      width: 100%;
    }
  }
}
</style>
